<?php
/**
 * Created by PhpStorm.
 * User: Lenovo
 * Date: 2019/4/27
 * Time: 19:28
 */

namespace app\api\controller;



use app\api\model\IndentModel;
use app\api\model\IndentQxModel;
use app\api\model\UserModel;
use app\api\model\YuyueModel;
use app\services\MessageServices;
use app\api\model\BankModel as Bank;
use app\api\model\QrcodeModel as Qrcode;

class Order extends Base
{
    private $time=10;//用户可抢单时间
    protected $user;
    protected $bank;
    public function __construct()
    {
        parent::__construct();
        $this->user = new UserModel();
        $this->bank = new Bank();
        $this->qrcode = new Qrcode();
    }
    public function test()
    {
        $uid=$this->uid;//用户id
        $re=MessageServices::pushmessage($uid,2,7);
    }
    //抢单排队
    public function grabSingle()
    {
        $uid=$this->uid;//用户id
        $userInfo = $this->user->getInfo(array("uid"=>$uid));
         if($userInfo['u_ztnum'] == 0){
            $this->error('请先完善个人信息','',-1);
         }
         if($userInfo['u_money'] <= 0){
             $this->error('您的保证金不足','',"-10053");
         }
        $type=!empty(input('type'))?input('type'):$this->error('参数错误','',3);//付款方式
        if($type == 3){
            $list = $this->bank->where("uid",$uid)->where("b_state",1)->select();
            if(empty($list)){
                $this->error('您还没有添加银行卡','',"-10051");
            }
        }else{
            $qrcodelist = $this->qrcode->where("uid",$uid)->where("q_state",1)->where("zid",$type)->select();
            if(empty($qrcodelist)){
                $this->error('您还没有添加二维码','',"-10052");
            }
        }
        $yuyue=YuyueModel::where('uid',$uid)->where('y_state','in','0,3,2')->count();//查询排位预约信息
        if($yuyue==0){//预约表没有该会员预约信息才可重新排队
            $re=YuyueModel::insert([
                'uid'=>$uid,
                'zid'=>$type,
            ]);
            if($re){
                //判断之前有么有因排队人数少 停止的推送订单
//                $indent=IndentModel::where('sort',$re->yid)->select();
//                if(!empty($indent)){
//                    foreach ($indent as $k){
//                        $this->delivery($k['tid']);
//                    }
//                }
                $this->success('抢单成功','',1);
            }else{
                $this->error('抢单失败','',0);
            }
        }else{
            $this->error('不可重复抢单','',-2);
        }
    }
    //抢单
    public function takeOrder()
    {
        $uid=$this->uid;//用户id
        $yid=!empty(input('yid'))?input('yid'):$this->error('参数错误','',3);//预定id
        $tid=!empty(input('tid'))?input('tid'):$this->error('参数错误','',3);//订单id
        $shiwu=new YuyueModel();
        $shiwu->startTrans();//开启事务
        $yuyue=YuyueModel::where('yid',$yid)->where('y_state',2)->find();//该会员的预定信息
        $indent=IndentModel::where('tid',$tid)->find();//订单信息
        if($yuyue){
            $yuyue->y_state=3;//排位预定信息改为已完成（已接单）
            $re1=$yuyue->save();
            $re2=IndentModel::where('tid',$tid)
                ->update([//订单与该会员的关联
                  'uid'=>$uid,
                  'z_jietime'=>date('Y-m-d H:i:s'),
                  'sid'=>2
                ]);
            $re3=UserModel::where('uid',$uid)->setDec('u_money',$indent['t_money']);//减去用户的保证金
            if($re1&&$re2&&$re3){
                $shiwu->commit();//提交事务
                $this->success('抢单成功','',1);
            }else{
                $shiwu->rollback();//提交事务
                $this->error('抢单失败','',0);
            }
        }else{
            $this->error('已过抢单时间','',-1);
        }
    }
    //确认已给平台打款
    public function sendMoney()
    {
        $tid=!empty(input('tid'))?input('tid'):$this->error('参数错误','',3);//订单id
        $indent=IndentModel::where('tid',$tid)->where('sid',5)->find();//订单信息
        if($indent){
            $indent->sid=6;//订单状态改为汇款完成
            $re=$indent->save();
            if($re){
                $this->success('确认成功','',1);
            }else{
                $this->error('确认失败','',-1);
            }
        }else{
            $this->error('订单错误','',-1);
        }
    }
    //确认已收到平台打款
    public function getMoney()
    {
        $tid=!empty(input('tid'))?input('tid'):$this->error('参数错误','',3);//订单id
        $indent=IndentModel::where('tid',$tid)->where('sid',4)->find();//订单信息
        if($indent){
            $indent->sid=5;//订单状态改为确认收款
            $re=$indent->save();
            if($re){
                $this->success('确认成功','',1);
            }else{
                $this->error('确认失败','',-1);
            }
        }else{
            $this->error('订单错误','',-1);
        }
    }
    //用户未接单 或者超时 取消用户对该订单确认状态
    public function cancel()
    {
        $yid=!empty(input('yid'))?input('yid'):$this->error('参数错误','',3);//预定id
        $shiwu=new YuyueModel();
        $shiwu->startTrans();//开启事务
        $yuyue=YuyueModel::where('yid',$yid)->find();
        $indent=IndentModel::where('tid',$yuyue['tid'])->find();
        $re1=YuyueModel::where('yid',$yid)//将用户接单改为排队状态
            ->where('y_state',2)
            ->update([
                'tid'=>'',
                'y_state'=>0
            ]);
        $re2=IndentQxModel::create([//添加取消订单
                                 't_number'=>$indent['t_number'],
                                 't_money'=>$indent['t_money'],
                                 'z_name'=>$indent['z_name'],
                                 'uid'=>$yuyue['uid'],
                                 'zid'=>$indent['zid'],
                                 'z_createtime'=>$indent['z_createtime']
                            ]);
        if($re1&&$re2){
            $this->delivery($indent['tid']);
            $shiwu->commit();//开启事务
            $this->success('取消成功','',1);
        }else{
            $shiwu->rollback();//开启事务
            $this->error('取消失败','',0);
        }
    }
    //寻找符合条件的抢单用户
    public function delivery($tid)
    {
        $indent=IndentModel::where('tid',$tid)->find();//订单信息
        $yuyue=YuyueModel::alias('a')
            ->join('jc_user b','a.uid=b.uid','left')
            ->where('a.zid',$indent['zid'])
            ->where('b.u_money','>',$indent['t_money'])
            ->where('yid','>',$indent['sort'])
            ->order('yid asc')
            ->field('a.*,b.u_money')
            ->find();
        if(!empty($yuyue)){//下面还有排队等单的人 就执行
            $re=YuyueModel::where('yid',$yuyue['yid'])//订单传递给下一个人
            ->update([
                'tid'=>$tid,
                'y_state'=>2
            ]);
          	$re2=IndentModel::where('tid',$tid)->update(['sort'=>$yuyue['yid']]);
            if($re&&$re2){//向下一个人推送消息
                //TODO ADFSA
                $re=MessageServices::pushmessage($yuyue['uid'],$tid,$yuyue['yid']);
             	if($re=="ok"){
                	return true;
                }else{
                	return false;
                }
            }
        }
    }
}